<?php
namespace amap;

use think\Request;

class Location
{
    static protected $key='5345679065294195ba7bf28e162ab54e';
    static function getLocation($address,$city){
        $key=self::$key;
        if(empty($address)){
            return null;
        }
        $url="https://restapi.amap.com/v3/geocode/geo?key={$key}&address={$address}&city={$city}";
        $data=curl($url);
        if($ret=json_decode($data,true)){
            if(isset($ret['geocodes'][0]['location'])){
                $ret['geocodes'][0]['location']=explode(',',$ret['geocodes'][0]['location']);
                return [
                    'full_address'=>$ret['geocodes'][0]['formatted_address'],
                    'lon'=>$ret['geocodes'][0]['location'][0],
                    'lat'=>$ret['geocodes'][0]['location'][1],
                ] ;
            }
        }
        return null;
    }

    static function getAddress($lon,$lat){
        if(empty($lon) || empty($lat)){
            return null;
        }
        $key=self::$key;
        $url="https://restapi.amap.com/v3/geocode/regeo?location={$lon},{$lat}&key={$key}&radius=1000&extensions=base";
        $data=curl($url);
        if($ret=json_decode($data,true)){
            if(!empty($ret['status'])){
                return [
                    'full_address'=>empty($ret['regeocode']['formatted_address'])?'':$ret['regeocode']['formatted_address'],
                    'country'=>empty($ret['regeocode']['addressComponent']['country'])?'':$ret['regeocode']['addressComponent']['country'],
                    'province'=>empty($ret['regeocode']['addressComponent']['province'])?'':$ret['regeocode']['addressComponent']['province'],
                    'city'=>empty($ret['regeocode']['addressComponent']['city'])?'':$ret['regeocode']['addressComponent']['city'],
                    'area'=>empty($ret['regeocode']['addressComponent']['district'])?'':$ret['regeocode']['addressComponent']['district'],
                    'township'=>empty($ret['regeocode']['addressComponent']['township'])?'':$ret['regeocode']['addressComponent']['township'],
                ];
            }
        }
        return null;
    }

    static function getIpInfo($ip=''){
        $key=self::$key;
        if(empty($ip)){
            $ip=Request::instance()->ip();
        }
        $url="https://restapi.amap.com/v3/ip?ip={$ip}&output=xml&key={$key}";
        $data=curl($url);
        if($ret=json_decode($data,true)){
            if(!empty($ret['status'])){
                return [
                    'province'=>$ret['province'],
                    'city'=>$ret['city']
                ];
            }
        }
        return null;

    }
}

